package com.appkubes.portal.admin.application.customer.service.impl;

import com.appkubes.common.exception.BusinessException;
import com.appkubes.portal.admin.application.auth.service.KeyCloakUserService;
import com.appkubes.portal.admin.application.customer.entity.vo.CustomerAppAddVO;
import com.appkubes.portal.admin.application.customer.service.CustomerAppService;
import com.appkubes.portal.core.entity.PortalCustomer;
import com.appkubes.portal.core.entity.PortalCustomerApp;
import com.appkubes.portal.core.entity.PortalGlobalApp;
import com.appkubes.portal.core.service.BasePortalCustomerService;
import com.appkubes.portal.core.service.BasePortalGlobalAppService;
import com.appkubes.portal.core.service.impl.BasePortalCustomerAppServiceImpl;
import org.keycloak.representations.idm.UserRepresentation;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class CustomerAppServiceImpl extends BasePortalCustomerAppServiceImpl implements CustomerAppService {
    @Resource
    BasePortalCustomerService customerService; //用户服务
    @Resource
    BasePortalGlobalAppService globalAppService;//配置信息
    @Resource
    KeyCloakUserService keyCloakUserService;

    /**
     * 添加应用
     *
     * @param appAddVO
     * @return
     * @throws BusinessException
     */
    @Override
    @Transactional
    public Boolean add(CustomerAppAddVO appAddVO) throws BusinessException {
        //检查用户是否存在
        UserRepresentation userRepresentation = keyCloakUserService.getUserRepresentationById(appAddVO.getCustomerKey());
        if (userRepresentation == null) {
            throw new BusinessException("找不到该用户");
        }
        PortalGlobalApp configApp = globalAppService.getById(appAddVO.getAppType());
        if (configApp == null) {
            throw new BusinessException("找不到应有类型");
        }

        PortalCustomerApp customerApp = new PortalCustomerApp();
        BeanUtils.copyProperties(appAddVO, customerApp);
        this.save(customerApp);
        return null;
    }
}
